<template>
  <!-- 主业预审列表&主业计划审核列表 -->
  <div class="main-review-comp page-container">
    <div class="flex-auto overflow-y">
      <div class="full-height full-width no-scroll-x no-scroll-y flex-column">
        <data-list ref="dataList" :cacheParam="true" :dataConfig="dataConfig" :tableData="tableData"></data-list>
        <upload-file ref="uploadFile" :uploadConfig="uploadConfig" @success="uploadSuccess"></upload-file>
      </div>
    </div>
  </div>
</template>

<script>
import DataList from '@/components/business/page-comp/data-list/data-list.vue';
import UploadFile from '@/components/business/page-comp/upload-file/upload-file.vue';
import api from '../api/index.js';
export default {
  name: 'MainReview',
  components: { DataList, UploadFile },
  props: {
    detailUrl: {
      type: String,
      default() {
        return ''
      },
    },
  },
  data() {
    return {
      tableData: {
        data: [],
        total: 0
      },
      dataConfig: {},
      uploadConfig: {}
    };
  },
  computed: {
    userToken() {
      return this.$store.getters.userToken;
    },
  },
  created() {
    this.REVIEW_STATUS = [];
    for (let key in (this.$config.REVIEW_STATUS || {})) {
      this.REVIEW_STATUS.push({ ...this.$config.REVIEW_STATUS[key] });
    }
    this.uploadConfig = {
      title: '上传主业审核文件',
      labelWidth: '120px',
      inputWidth: '260px',
      action: '/plan/generateMainTask',
      multiple: false,
      limit: 1,
      accept: '.xls,.xlsx',
      uploadTips: '只能上传.xls/.xlsx文件，且不超过10MB',
      form: {
        // 任务类型，枚举值如下
        // 1：手动excel导入任务
        // 2：手动同步外部数据任务
        taskType: 1,
      },
      conditions: [
        // {
        //   label: '测试字段',
        //   prop: 'test',
        //   type: 'input',
        // },
        {
          label: '主业审核文件',
          prop: 'fileStream',
          type: 'file',
        },
      ],
    };
    // 设置data-list配置
    this.dataConfig = {
      search: {
        labelWidth: '100px',
        loading: false,
        form: {
          taskType: '1',
          status: '',
          fileName: ''
        },
        conditions: [
          {
            label: '审核状态',
            prop: 'status',
            type: 'select',
            options: this.REVIEW_STATUS,
          },
          {
            label: '文件名',
            prop: 'fileName',
            type: 'input',
          },
        ],
        searchCB: this.search,
        topOperates: [
          {
            type: 'button',
            label: '上传主业审核文件',
            callback: this.uploadFile,
          },
          {
            type: 'link',
            label: '主业审核文件模板下载',
            callback: this.downloadFile,
            underline: true,
          },
        ]
      },
      table: {
        config: {
          select: false,
          selectCallback: () => { }
        },
        columns: [
          {
            label: '审核文件名称',
            prop: 'fileName',
            type: 'text',
          },
          {
            label: '审核状态',
            prop: 'status',
            type: 'text',
            width: '220',
            hasProgress: true,
            callback: (item) => {
              return this.getStatusText(item.status);
            },
          },
          {
            label: '上传时间',
            prop: 'createtime',
            type: 'text',
            width: '200',
          },
          {
            label: '上传人',
            prop: 'userName',
            type: 'text',
            width: '180',
          },
          {
            label: '操作',
            prop: 'status',
            type: 'operates',
            fixed: 'right',
            width: '380',
            operates: [
              {
                label: '明细查询',
                type: 'link',
                callback: this.showDetail,
                show: (item) => {
                  // 明细查询按钮只有当状态不是“待审核”时才展示
                  return String(item.status) !== this.$config.REVIEW_STATUS.BEFOREREVIEW.value;
                }
              },
              {
                label: '审核结果下载',
                type: 'link',
                callback: this.downloadResult,
                show: (item) => {
                  // 审核结果下载按钮只有当状态为“审核完成”时才展示
                  return String(item.status) === this.$config.REVIEW_STATUS.REVIEWED.value;
                }
              },
              {
                label: '强制结束',
                type: 'link',
                callback: this.forceEnd,
                show: (item) => {
                  // 强制结束按钮只有当状态为“审核中”时才展示
                  return String(item.status) === this.$config.REVIEW_STATUS.REVIEWING.value;
                }
              },
              {
                label: '删除',
                type: 'link',
                callback: this.deleteRow,
                show: (item) => {
                  // 删除按钮只有当状态为“待审核”时才展示
                  return String(item.status) === this.$config.REVIEW_STATUS.BEFOREREVIEW.value || String(item.status) === this.$config.REVIEW_STATUS.STOP.value || String(item.status) === this.$config.REVIEW_STATUS.REVIEWED.value;
                }
              },
            ]
          },
        ],
      }
    };
  },
  mounted() {
    this.initSocket();
    this.$refs['dataList'].search();
  },
  beforeDestroy() {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.$log.info('关闭当前页面的WebSocket连接');
      this.socket.close();
    }
  },
  methods: {
    initSocket() {
      // 获取系统配置
      const wsUrl = this.$utils.getSocketUrl('/plan/ws/mainTaskProcess?token=' + this.userToken);
      this.socket = new WebSocket(wsUrl);
      this.socket.onopen = (e) => {
        this.$log.info("WebSocket已连接：", e);
      };
      this.socket.onmessage = (e) => {
        this.$log.info("收到WebSocket消息：", e);
        this.refreshProgress(JSON.parse(e.data));
      };
      this.socket.onerror = (e) => {
        this.$log.info("WebSocket异常，错误信息：", e);
      };
      this.socket.onclose = (e) => {
        this.$log.info("WebSocket连接关闭：", e);
      };
    },
    refreshProgress(data) {
      const progressValue = Number((data.progress || '').split('%')[0]);
      this.tableData.data.forEach(item => {
        if (data.taskId === item.id) {
          // 如果当前任务有进度，则将状态改为“审核中”
          item.status = this.$config.REVIEW_STATUS.REVIEWING.value;
          item.hasProgress = true;
          item.progressValue = progressValue;
          // 审核进度100%时，将审核状态修改为审核完成，并将进度条隐藏
          if (progressValue === 100) {
            item.status = this.$config.REVIEW_STATUS.REVIEWED.value;
            item.hasProgress = false;
          }
        }
      });
    },
    getStatusText(status) {
      return (this.REVIEW_STATUS.find(item => {
        return String(item.value) === String(status);
      }) || {}).name;
    },
    showDetail(item) {
      this.$router.push({ path: `${this.detailUrl}`, query: { id: item.id } });
    },
    downloadResult(item) {
      const filePath = item.resultFilePath;
      if (!filePath || !filePath.length) {
        this.$message.error(`主业审核结果下载失败，文件内容为空`);
        return;
      }
      const fileName = filePath.split('/')[filePath.split('/').length - 1];
      this.$log.debug(`主业审核结果文件为：`, fileName);
      api.downResultExcelFile({
        filePath
      })
        .then((res) => {
          this.$log.debug(`主业审核结果下载，文件大小为：`, res.data.size);

          if (!res.data.size) {
            this.$message.error(`主业审核结果下载失败，文件内容为空`);
            return;
          }

          this.$utils.downloadBlobFile(fileName, res.data);

          this.$message.success(`主业审核结果下载成功`);
        })
        .catch((e) => {
          this.$log.error(`主业审核结果下载失败，错误信息为：`, e);
        });
    },
    forceEnd(item) {
      this.$confirm(`确认强制结束该审核任务?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.forceFailReviewMainTask({
            id: item.id
          })
            .then((res) => {
              if (res.success) {
                this.$log.debug(`审核任务强制结束成功`);
                this.$message.success(`审核任务强制结束成功`);
                this.$refs['dataList'].search();
              } else {
                this.$log.error(`审核任务强制结束失败，错误信息为：`, res.message);
                this.$message.error(`审核任务强制结束失败：` + (res.message || ''));
              }
            })
            .catch((e) => {
              this.$log.error(`审核任务强制结束失败，错误信息为：`, e);
            });
        }).catch((e) => {
          this.$log.debug(`取消审核任务强制结束操作`, e);
        });
    },
    deleteRow(item) {
      this.$confirm(`确认删除该审核任务?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.deleteMainTask({
            id: item.id
          })
            .then((res) => {
              if (res.success) {
                this.$log.debug(`审核任务删除成功`);
                this.$message.success(`审核任务删除成功`);
                this.$refs['dataList'].search();
              } else {
                this.$log.error(`审核任务删除失败，错误信息为：`, res.message);
                this.$message.error(`审核任务删除失败：` + (res.message || ''));
              }
            })
            .catch((e) => {
              this.$log.error(`审核任务删除失败，错误信息为：`, e);
            });
        }).catch((e) => {
          this.$log.debug(`取消审核任务删除操作`, e);
        });
    },
    uploadFile() {
      this.$refs['uploadFile'].open();
    },
    downloadFile() {
      // 调用通用文件下载接口
      this.$utils.downloadFileByFileName('主业审核文件模板.xlsx');
    },
    uploadSuccess() {
      this.$refs['dataList'].search();
    },
    search(pageInfo, searchForm) {
      this.dataConfig.search.loading = true;
      const params = {
        ...pageInfo,
        ...searchForm,
      };
      api.queryMainTasks(params)
        .then((res) => {
          this.dataConfig.search.loading = false;
          if (res.success) {
            this.$log.debug('查询主业计划审核任务列表成功');
            const dataList = (res.data.mainTaskList || []);
            dataList.forEach(item => {
              // 如果状态为“待审核”和“审核中”，则展示进度条
              // if (item.status === this.$config.REVIEW_STATUS.REVIEWING.value || item.status === this.$config.REVIEW_STATUS.BEFOREREVIEW.value) {
              if (item.status === this.$config.REVIEW_STATUS.REVIEWING.value) {
                item.hasProgress = true;
              }
              // 不管为什么状态，初始都审核进度为0%，待接收到websocket消息后，刷新进度值
              item.progressValue = 0;
            });
            this.tableData = { data: dataList, total: res.data.total };
          } else {
            this.$log.error('查询主业计划审核任务列表失败，错误信息为：', res.message);
            this.$message.error('查询主业计划审核任务列表失败：' + (res.message || ''));
          }
        })
        .catch((e) => {
          this.dataConfig.search.loading = false;
          this.$log.error('查询主业计划审核任务列表失败，错误信息为：', e);
        });
    },
  }
};
</script>

<style lang="scss" scoped>.main-review-comp {}</style>
